#!/usr/bin/python
# -*- coding: utf-8 -*-

############################################################################
#    Copyright (C) 2007-2010 by Zolotarevsky Alexander(ALex-AnNet)         #
#    alex7annet@gmail.com                                                  #
#                                                                          #
#    This program is free software; you can redistribute it and#or modify  #
#    it under the terms of the GNU General Public License as published by  #
#    the Free Software Foundation; either version 2 of the License, or     #
#    (at your option) any later version.                                   #
#                                                                          #
#    This program is distributed in the hope that it will be useful,       #
#    but WITHOUT ANY WARRANTY; without even the implied warranty of        #
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         #
#    GNU General Public License for more details.                          #
#                                                                          #
#    You should have received a copy of the GNU General Public License     #
#    along with this program; if not, write to the                         #
#    Free Software Foundation, Inc.,                                       #
#    59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             #
############################################################################

import sys
import tempfile
import os
import types
from depack.colorlib import *

#config = "/home/alex/projects/myProject/depack/depack-encore/config"
config = "/etc/depack/config"



is_variable    = {'colorize':None, 'sign_pack':None, 'sign_files':None}
comment = "#"


def del_comment(str_par):
   num = 0
   liter = 0
   for i in str_par:
      if i == '"':
         liter += 1
         if liter == 2:
            liter = 0

      if i == comment:
         if liter == 0:
            str_par = str_par[:num]
            break

      num += 1

   return str_par


def find_section(str_file):
   str_file = del_comment(str_file)
   str_file = str_file.strip().lower().replace('\t', ' ')
   if str_file[0] == '[':
      if str_file[-1] == ']':
         return str_file

   return "null"
#def find_section(str_file)

def check_str_param(str_par, mesdic):

   spars = 0
   sarg  = 0

   
   if len(str_par) == 0:
      return [0, 0]

   str_par = del_comment(str_par)
   source_str_par = str_par.replace("\n", "")
   str_par = str_par.split('"')

   
   for part in str_par[2::2]:
      if part.strip() != "":
         print mesdic['mes_err_syntax'] + " '" + source_str_par + "'"
         return [0, 0]

   
   part = str_par[-1].strip()
   if part.strip() != "":
      print mesdic['mes_err_syntax'] + " '" + source_str_par + "'"
      return [0, 0]

   if str_par[0].strip() != "":
      
      part = str_par[0].strip().replace('\t', ' ')     
      part = part.split(" ")
      if len(part) > 1:
         print mesdic['mes_err_name_var'] + " '" + source_str_par + "'"
         return [0, 0]

      sarg = 1

   spars = len(str_par) / 2

   return [sarg, spars]
#def check_str_param(str_par)


def  check_str(str_par, mesdic):

   
   if len(str_par) == 0:
      return 0

   str_par = del_comment(str_par)
   source_str_par = str_par.replace("\n", "")
   str_par = str_par.split('"')

   if len(str_par) != 1:
      if len(str_par)%2 != 0:
         if str_par[0].strip() == "":

            
            for part in str_par[0::2]:
               if part.strip() != "":
                  print mesdic['mes_err_syntax'] + " '" + source_str_par + "'"
                  return 0

            
            part = str_par[-1].strip()
            if part.strip() != "":
               print mesdic['mes_err_syntax'] + " '" + source_str_par + "'"
               return 0

            return 2;

         else:

            
            for part in str_par[2::2]:
               if part.strip() != "":
                  print mesdic['mes_err_syntax'] + " '" + source_str_par + "'"
                  return 0

            
            part = str_par[0].strip().replace('\t', ' ')     
            part = part.split(" ")
            if len(part) > 1:
               print mesdic['mes_err_name_var'] + " '" + source_str_par + "'"
               return 0

            
            part = str_par[-1].strip()
            if part.strip() != "":
               print mesdic['mes_err_syntax'] + " '" + source_str_par + "'"
               return 0

            return 1;

      else:
         print mesdic['mes_err_syntax'] + " '" + source_str_par + "'"
         return 0

   else:
      print mesdic['mes_err_syntax'] + " '" + source_str_par + "'"
      return 0
#def check_str(str_par)


def get_variable(str_par, check_var_name, list_var , mesdic):
   str_par = del_comment(str_par)
   source_str_par = str_par.replace("\n", "")

   str_par = str_par.split('"')
   str_par = str_par[0].strip().lower()

   if check_var_name == True:
      if list_var.has_key(str_par) == True:
         return str_par

      else: 
         print mesdic['mes_err_unknown_var'] + " '" + source_str_par.replace('\n', '').strip() + "'"
         return "null"

   else:
      return str_par
#def get_variable(str_par, section)


def get_value(str_par):
   str_par = del_comment(str_par)
   str_par = str_par.split('"')
   var_box = []
   for part in str_par[1::2]:
      var_box.append(part)
   return var_box
#def get_value(str_par, section)


def treatment_str(str_par, section, colp, arg, mesdic):
   source_str_par = str_par.replace("\n", "")
   check = check_str_param(str_par, mesdic)
   if check[1] == 0:
      return ['', 0]
      
   if check[0] == 1:
      if colp == 0:
         colp += check[1]
         if colp > section.colp:
            print mesdic['mes_err_syntax'] + " '" + source_str_par + "'"
            return ['', 0]
         
         arg = get_variable(str_par, section.check_var, section.list_var, mesdic)
         value = get_value(str_par)

      else:
         print mesdic['mes_err_syntax'] + " '" + source_str_par + "'"
         return ['', 0]

      section.var[arg] = value

      if colp == section.colp:
         colp = 0
         arg = "null"

   elif check[1] > 0:
      if arg != "null":
         colp += check[1]
         if colp > section.colp:
            print mesdic['mes_err_syntax'] + " '" + source_str_par + "'"
            return ['', 0]
         
         value = get_value(str_par)
         section.var[arg] += value

         if colp == section.colp:
            colp = 0
            arg = "null"
      else:
         print mesdic['mes_err_syntax'] + " '" + source_str_par + "'"
         return ['', 0]

   elif check[0] == 0:
      if check[1] == 0:
         arg = "null"

   return [arg, colp]
#def treatment_str(str_par, section, colp, arg)


def print_sect(sect):

   print "[" + sect.name + "]"

   for i in sect.var.keys():
      print ">>> " + i
      for j in sect.var[i]:
         print "       " + j

#def print_sect(section)



def SetArch(arch, mesdic):
   try:
      file = open(config)

   except:
      print mesdic['mes_err_file'] + ' ' + config
      sys.exit(2)
   
   box_str = []

   is_set_arch = False
   for str_file in file:
      str_nocom = del_comment(str_file)
      str_nocom = str_nocom.strip()
      str_nocom = str_nocom[:4]
      if str_nocom == "arch":
         box_str.append('\tarch\t\t"' + arch + '"\n')
         is_set_arch = True
      else:
         box_str.append(str_file)

   file.close()

   try:
      file = open(config, 'w')

   except:
      print mesdic['mes_err_file'] + ' ' + config
      sys.exit(2)

   for str in box_str:
      file.write(str)

   file.close()

   if is_set_arch:
      print mesdic['mes_set_arch']
   else:
      print mesdic['mes_err_set_arch']

#def SetArch(arch)




def VSearch(fil, path, folder, mesdic):

   
   tempf = tempfile.mktemp()

   if folder:
      os.system("ls '" + path + "' | grep '" + fil + "' > " + tempf)
   else:
      os.system("cat '" + path + "' | grep '" + fil + "' > " + tempf)

   try:
      file = open(tempf)
   except:
      print mesdic['mes_err_file'] + " tempf"
      sys.exit(2)

   
   str = file.readline()

   
   while str != '':

      if str.strip() == fil.strip():

         return True

      str = file.readline()

   file.close()
   return False
#def VSearch(file, path)


def is_file(fl, dir):

   for fle in os.listdir(dir.strip()):

      if fl.strip() == fle.strip():
         return 1

   return 0
#def is_file(fl, dir)

def is_title(title, dir, mesdic):

   for fle in os.listdir(dir.strip()):

      try:
         file = open(dir + '/' + fle)
      except:
         print mesdic['mes_err_file'] + ' ' + path_base + '/' + fle
         sys.exit(2)

      str = file.readline()

      file.close()

      
      titl = ''
      if str.find('<title>') > -1:
         str_title = str.split('<title>')

         if str_title[1].find('</title>') > -1:
            str_title = str_title[1].split('</title>')
            titl = str_title[0].strip()

      if titl == '':
         continue

      if titl.strip() == title.strip():
         return 1

   return 0
#def is_title(title, dir)

def DigtoChar(dig):

   if   dig == 0:
      return '0'
   elif dig == 1:
      return '1'
   elif dig == 2:
      return '2'
   elif dig == 3:
      return '3'
   elif dig == 4:
      return '4'
   elif dig == 5:
      return '5'
   elif dig == 6:
      return '6'
   elif dig == 7:
      return '7'
   elif dig == 8:
      return '8'
   elif dig == 9:
      return '9'
#def DigtoChar(dig)

def to_str(dig):

   str = ''

   while dig != 0:

      str += DigtoChar(dig % 10)
      dig = int(dig / 10)

      return str
#def to_str(dig)

def GetTitle(fl):

   titl = ''

   try:
      file = open(fl)
   except:
      return titl

   str = file.readline()

   file.close()

   
   if str.find('<title>') > -1:
      str_title = str.split('<title>')

      if str_title[1].find('</title>') > -1:
         str_title = str_title[1].split('</title>')
         titl = str_title[0].strip()
   
   return titl
#def GetTitle(fl)

def is_root(mesdic):

   if os.environ['USER'] != 'root':
      print mesdic['mes_err_root']

      sys.exit(2)
#def is_root()


def find_desc(str, use):
   str = str.strip()

   if len(str) != 0:

      if str[0] != '#':
         s = str.split(' - ', 1)

         if s[0].strip() == use.strip():
            no_com = s[1].split('#', 1)
            s[1] = no_com[0]

            return s

   return []
#def find_desc(str, use)


def find_local_desc(str, use):
   str = str.strip()

   if len(str) != 0:

      if str[0] != '#':
         s = str.split(' - ', 1)
         name_use = s[0].split(':')

         if name_use[1].strip() == use.strip():
            no_com = s[1].split('#', 1)
            s[0] = name_use[0].strip()
            s[1] = name_use[1].strip()
            s.append(no_com[0])

            return s

   return []
#def find_local_desc(str, use)


def find(box, elem):
   elem = elem.replace('-', '');
   elem = elem.replace('*', '');

   for i in box:

      if i.replace('-', '') == elem:
         return 1

   return 0
#def find(box, elem)


def delete(box, elem):
   elem = elem.replace('-', '');
   elem = elem.replace('*', '');

   box_upd = []

   for i in box:

      if i.replace('-', '') != elem:
         box_upd += [i]

   return box_upd
#def delete(box, elem)

def SetColor(color, str, status):
   if status == 1:
      return colorize(color, str)
   else:
      return str
#def SetColor(color, str, status)

def SigStop(signum, frame):

   pass

#def SigStop()
